<html>
	<script src="js/jquery-1.5.2.min.js"></script>
	<script>
		var curTabId = -1;
		var curUrl = "";
		var timer = -1;
		var duration = 0;
		chrome.tabs.onSelectionChanged.addListener(function(tabId, selectInfo){
/*				var nextUrl;
				chrome.tabs.get(tabId, function(tab){
					nextUrl = tab.url;
				});
				
				clearTimer();
//				alert("tab selection change");
				calDuration(curUrl, duration, "selection change");
				duration = 0;
				curUrl = nextUrl;
				curTabId = tabId;
				timer = setInterval(updateDuration, 1000);
				*/
//				alert("on selection changed");
				alert(localStorage["cur_time"]);
				//				timer = setInterval(updateDuration, 1000);
				$("#timer_box").text(localStorage["cur_time"]);
			});
		chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab){
				if ( changeInfo.status == "loading" )
					return;
/*
				nextUrl = tab.url;
				clearTimer();
				calDuration(curUrl, duration, "update");
				duration = 0;
				curUrl = nextUrl;
				curTabId = tabId;
				timer = setInterval(updateDuration, 1000);
				*/

				var port = chrome.tabs.connect(tabId, {name: "knockknock"});
				chrome.extension.onConnect.addListener(function(port) {
					port.onMessage.addListener(function(msg) {
						alert(msg);				
					});
				});

			});
/*
		chrome.tabs.onRemoved.addListener(function(tabId, removeInfo){
				if ( tabId != curTabId )
					return;
				clearTimer();
				alert("tab remove");
				calDuration(curUrl, duration, "remove");
				duration = 0;
				timer = curTabId = -1;
				curUrl = "";
			});
*/

	function updateDuration()
	{
//		duration += 1;
//		alert(duration);
		localStorage["cur_time"] = new Date();
//		alert(localStorage["cur_time"]);
	}

	function checkUrl(shortUrl, longUrl)
	{
/*
		if ( longUrl.indexOf(shortUrl) == 0 )
			return true;
		return false;
*/
		return longUrl.match(shortUrl);
	}

	function clearTimer()
	{
		if ( timer != -1 )
		{
			window.clearInterval(timer);
			timer = -1;
		}
	}
	
	function calDuration(url, duration, msg)
	{
//		alert(url + " " + duration + " " + msg);
		var urlInList = matchUrl(url);
		if ( urlInList == "" )
			return;
		var storePath = urlInList+".duration";
		var curDuration = localStorage[storePath];
		if ( curDuration == null )
			localStorage[storePath] = duration;
		else
			localStorage[storePath] = Number(curDuration) + duration;
//		alert(localStorage[storePath]);
	
	}

	function matchUrl (url)
	{
		var urls = localStorage['urlList'].split(",");
		for (var i = 0; i < urls.length; i ++)
		{
/*			if ( urls[i] != "" && url.(urls[i]) )
			{
//				alert("found url");
				return urls[i];
			}
			*/
		}
		return "";
	}
	</script>
</html>
